'use strict'

import { app, protocol, BrowserWindow, ipcMain, Menu, Tray, globalShortcut as gs, dialog } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'

import { runExec, stopServer } from './electron/utils'
import { mainWinHandler } from './electron/mainWin'

// let serverProcess = runExec('node app', 'D:/NeteaseCloudMusicApi-master')
// setTimeout(() => {
//   stopServer(serverProcess)
// }, 1500);


let mainWin = null
let loginWin = null
let lodingWin = null

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 1122,
    height: 670,
    minWidth: 1122,
    minHeight: 672,
    alwaysOnTop: false,
    resizable: true, // 禁止改变主窗口尺寸,设置过后，win.isMaximized()总是返回false
    show: false, // 一开始是false,loadpage加载完毕的时候为true
    autoHideMenuBar: true,// 隐藏工具栏
    frame: false,
    icon: `${__static}/favicon.ico`,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      // nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION

      nodeIntegration: true,
      webSecurity: true // 允许跨域
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }

  // win.webContents.openDevTools()

  mainWin = win

  // win.on('ready-to-show', () => {
  //   console.log('main==ready')
  // })

  setTimeout(() => {
    createTray(win)
    initGs()
    win.show()
    lodingWin.hide()
  }, 2000);

  win.on('closed', () => {
    mainWin = null;
    app.quit();
  })

  mainWinHandler(win)

}


async function createLoginWindow() {
  if (loginWin) {
    loginWin.show()
    return false
  }
  loginWin = new BrowserWindow({
    parent: mainWin,
    modal: true,
    width: 380,
    height: 560,
    transparent: true,
    alwaysOnTop: true,
    maximizable: false, // 是否允许双击最大化
    resizable: false, // 禁止改变主窗口尺寸,设置过后，win.isMaximized()总是返回false
    show: true, // 一开始是false,loadpage加载完毕的时候为true
    autoHideMenuBar: true,// 隐藏工具栏
    frame: false,
    webPreferences: {
      devTools: true,
      nodeIntegration: true,
      webSecurity: true // 允许跨域
    }
  })
  // loginWin.setSkipTaskbar(false)

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await loginWin.loadURL(process.env.WEBPACK_DEV_SERVER_URL + '#/login')
  } else {
    loginWin.loadURL('app://./index.html' + '/#/login')
  }

  loginWin.on("closed", () => {
    loginWin = null;
  })
}

async function createLodingWindow() {
  lodingWin = new BrowserWindow({
    height: 400,
    width: 600,
    useContentSize: true,
    show: false,
    transparent: false,
    maximizable: false,  //禁止双击放大
    frame: false   // 去掉顶部操作栏
  })
  lodingWin.loadURL(`file://${__static}/loadpage.html`)

  lodingWin.on('closed', () => {
    lodingWin = null
  })

  lodingWin.once('ready-to-show', () => {
    console.log('loading==ready')
    lodingWin.show()
  })

}


// 设置托盘
function createTray(win) {
  //系统托盘图标
  // appTray = process.env.NODE_ENV === 'development' ? new Tray('build/icons/icon.ico') : new Tray(`${__static}/favicon.ico`);
  if (process.platform === 'win32') {
    //设置托盘图标和菜单
    var trayMenuTemplate = [
      {
        label: '打开',
        click: () => {
          win.show();
        }
      },
      {
        label: '重新加载',
        click: () => {
          win.reload()
        }
      },
      {
        label: '退出',
        click: () => {
          app.exit()
        }
      }
    ];

  };
  let appTray = new Tray(`${__static}/favicon.ico`);
  //图标的上下文菜单
  const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
  //设置此托盘图标的悬停提示内容
  appTray.setToolTip('土狗音乐托盘图标');
  //设置此图标的上下文菜单
  appTray.setContextMenu(contextMenu);
  //单击右下角小图标显示应用左键 
  appTray.on('click', () => {
    if (win.isVisible()) {
      win.focus()
    } else {
      win.show()
    }
  })
  //右键
  appTray.on('right-click', () => {
    appTray.popUpContextMenu(trayMenuTemplate);
  });
}

// 注册快捷键=
function initGs() {
  gs.unregisterAll()
  //  CommandOrControl win => ctrl
  gs.register('CommandOrControl+alt+s', () => {
    // 暂停OR播放音乐
    mainWin.webContents.send('change-music-play');
  })
}


// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})


ipcMain.on('show-login-win', () => {
  createLoginWindow()
})
ipcMain.on('login-success', (event, obj) => {
  mainWin.webContents.send('login-success', obj);
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
    createLodingWindow()
  }
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    // Devtools extensions are broken in Electron  6/7/<8.25 on Windows
    // See https://github.com/nklayman/vue-cli-plugin-electron-builder/issues/378 for more info
    // Electron will not launch with Devtools extensions installed on Windows 10 with dark mode
    // If you are not using Windows 10 dark mode, you may uncomment the following lines (and the import at the top of the file)
    // In addition, if you upgrade to Electron ^8.2.5 or ^9.0.0 then devtools should work fine

    // try {
    //   await installExtension(VUEJS_DEVTOOLS)
    // } catch (e) {
    //   console.error('Vue Devtools failed to install:', e.toString())
    // }

  }
  createWindow()
  createLodingWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
